<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Http\Models\Menu;


class MenuController extends Controller {


    public function index(Request $request)
    {
        $menus = $this->getMenuList();

        return view("admin.menu.index",['menus'=>$menus,'active'=>'menu']);
    }

    public function create(Request $request)
    {
        $menus = $this->getMenuList();
        return view('admin.menu.create',['menus'=>$menus,'active'=>'menu']);
    }

    public function store(Request $request){
        $menu = new Menu;
        $menu -> title = $request->input('title');
        $menu -> entitle = $request->input('entitle');
        $menu -> pid = $request -> input('pid');
        $menu -> url = $request -> input('url');
        $menu -> target = $request -> input('target');
        $menu -> position = $request -> input('position');
        $menu -> save();

        return redirect('/admin/menu');
    }

    public function edit($id){

        $menu = Menu::find($id);

        $menus = $this->getMenuList();

        return view('admin.menu.edit',['menu'=>$menu,'menus'=>$menus,'active'=>'menu']);
    }


    public function update(Request $request,$id)
    {
        $menu = Menu::find($id);
        $menu -> title = $request->input('title');
        $menu -> entitle = $request->input('entitle');
        $menu -> pid = $request -> input('pid');
        $menu -> url = $request -> input('url');
        $menu -> target = $request -> input('target');
        $menu -> position = $request -> input('position');

        if(intval($menu->pid) == intval($menu->id)){
            return $this->failure("/admin/menu/{$menu->id}/edit","不能作为自己的子菜单");
        }
        $menu -> save();

        return redirect('/admin/menu');
    }

    public function delete($id)
    {
        $res = Menu::destroy($id);
        if($res) return view('success',['url'=>'/admin/post']);

        return view('failure',['url'=>'/admin/post']);
    }


    private function getMenuList(){
        $all = Menu::all()->toArray();
        $menus = [];

        foreach($all as $key => $val){
            $menus[$val['id']] = $val;
        }

        $menus = $this->listMenuToTree($menus);
        return $menus;
    }

    //不是真正的树 树的效率没有这个高 本方法只需要遍历一遍 复杂度O(n)
    private function listMenuToTree( $listMenu )
    {
        foreach( $listMenu as $key => $val ){
            if(isset($listMenu[$val['pid']])){
                if(!@is_array($listMenu[$val['pid']]['sub'])) {
                  $listMenu[$val['pid']]['sub'] = array();
                }
                array_push($listMenu[$val['pid']]['sub'],$val);
            }
        }
        return $listMenu;
    }
}


